#! python 3.6

#########################################################
#| @File    :   envVar.py
#| @ClsName :   envVarViewSet
#| @Version :   1.0.0
#| @History :
#|----------------------------------------------------------------------------------------------------------|
#| version       | Type                | Author        | Contact                     | Time                 |
#|----------------------------------------------------------------------------------------------------------|
#| 1.0.0         | Create              | Tony.Don      | yeihizhi@163.com            | 2023-04-23 15:05:09  |
#|----------------------------------------------------------------------------------------------------------|
#| @License :   Apache-2.0
#| @Desc    :   Sys environ variable operation view.
#########################################################

# import lib by pypi
from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django.db.models import Q
from django.http import JsonResponse, QueryDict
from rest_framework import viewsets, routers
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.renderers import JSONRenderer
from rest_framework.decorators import *
from rest_framework.pagination import PageNumberPagination
# import lib by project
from core.config import REQUEST_MANAGER
from core.decorator.checkHttp import headerChecking
from core.log import logging
from api.models.envVar import envVar
from api.serializers.envVar import envVarSerializer,serializer_context,Response


#code start

class envVarViewSet(viewsets.ViewSet):
    queryset= envVar.objects.all().order_by('-id')
    serializer_class= envVarSerializer
    #pagination_class= PageNumberPagination
    #authentication_classes=None
    #permission_classes=None
    #throttle_classes=None

    def list(self,request):
        '''列表'''
        m_querySet= self.queryset
        pg = PageNumberPagination()
        m_page_result = pg.paginate_queryset(queryset=m_querySet, request=request, view=self)
        m_serializer = envVarSerializer(instance=m_page_result, many=True, context={'request': request})
        m_data = pg.get_paginated_response(m_serializer.data)
        return Response(stateCode=200,data=m_data.data)

    def create(self,request):
        '''新建'''
        serializer= envVarSerializer(data= request.data, context= serializer_context)
        if serializer.is_valid():
            if serializer.save():
                return Response(stateCode=200,data=serializer.data)
            else:
                return Response(stateCode=-1,data='create error.')
        else:
            return Response(stateCode=-1, data="error:%s"%serializer.errors)

    def retrieve(self,request,pk=None):
        '''获取一个对象'''
        if not pk:
            return Response(stateCode=-1,data="pk is none.")
        m_queryset = envVar.objects.filter(pk=pk)
        m_instance = get_object_or_404(m_queryset, pk=pk)
        m_serializer = envVarSerializer(instance=m_instance, context=serializer_context)
        return Response(stateCode=200,data=m_serializer.data)

    def update(self,request,pk=None):
        '''更新一个对象(全更新)'''
        try:
            if not pk:
                return Response(stateCode=-1, data="pk is none.")
            m_object= envVar.objects.get(pk= pk)
            serializer= envVarSerializer(data= request.data, instance= m_object, many= False)
            if serializer.is_valid():
                if serializer.save():
                    return Response(stateCode=200,data=serializer.data)
                else:
                    return Response(stateCode=-1,data='update error.')
            else:
                return Response(stateCode=-1, data="error:%s"%serializer.errors)
        except Exception as e:
            return Response(stateCode=-1,data="update system error.",error=e)

    def partial_update(self,request,pk=None):
        '''更新一个对象(部分更新)'''
        pass
    
    def destroy(self,request,pk=None):
        '''销毁一个对象'''
        try:
            if not pk:
                return Response(stateCode=-1,data="pk is none.")
            envVar.objects.get(pk= pk).delete()
            return Response(stateCode=200,data="success")
        except Exception as e:
            return Response(stateCode=-1,data="delete system error.",error=e)
    
    @action(methods=['GET'],detail=False)
    @headerChecking({"query.k"})
    def get_by_key(self,request):
        '''根据KEY获取值'''
        try:
            result= envVar.get_by_key(request.query_params["k"])
            if result:
                m_serializer= envVarSerializer(instance=result,serializer_context=request)
                Response(stateCode=200,data=m_serializer.data)
            else:
                logging.error("can not found 'key' with %s"%request.query_params["k"])
                Response(stateCode=-1,data="can not found 'key' with %s"%request.query_params["k"])
        except Exception as e:
            logging.error(e)
            return Response(stateCode=-1, data="get key has err.",error=e)
